package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private IEmployeeService employeeService;
    @Override
    public void save(Notice notice) {
        //获取当前人信息
        Employee currentUser = UserContext.getCurrentUser();
        notice.setCreateUser(currentUser);
        //设置创建的时间
        notice.setCreateTime(new Date());
        noticeMapper.insert(notice);
        //获取所有的员工
        List<Employee> employees = employeeService.listAll();
        //将所有的员工与公告关系添加到关系表,并且设置初始状态为未读
        for (Employee employee : employees) {
            noticeMapper.insertRelation(notice.getId(),employee.getId());
        }
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id, id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"en.readStatus"); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    @Override
    public void changeStatus(Long id, boolean status) {
        //将状态取反
        noticeMapper.changeStatus(id,!status);
    }
    @Override
    public Notice show(Long id) {
        //判断员工是否有读过
        Employee employee = UserContext.getCurrentUser();
        Long empId = employee.getId();
        Notice notice = noticeMapper.selectByPrimaryKey(id, empId);
        boolean readStatus = notice.isReadStatus();
        if (!readStatus){
            //设置状态已读
            noticeMapper.updateRelation(id,empId);
            //将session中员工未读信息进行更新
            employee.setNoReadMessage(employeeService.countNoReadMessageById(id));
            UserContext.setCurrentUser(employee);
        }
        return notice;
    }
}
